// Fill out your copyright notice in the Description page of Project Settings.


#include "GameEndWidget.h"
#include "Components/TextBlock.h"
#include "Components/Button.h"
#include "Blueprint/WidgetBlueprintLibrary.h"
#include "Kismet/GameplayStatics.h"

void UGameEndWidget::InitializeEndScreen(int32 TotalScore)
{
	if (TotalScoreText)
	{
		TotalScoreText->SetText(FText::AsNumber(TotalScore));
	}
}

void UGameEndWidget::OnRestartButtonClicked()
{
	CleanUpAllUI();
	UGameplayStatics::OpenLevel(GetWorld(), FName(*GetWorld()->GetName()));
}

void UGameEndWidget::NativeConstruct()
{
	Super::NativeConstruct();

	if (RestartGameButton)
	{
		RestartGameButton->OnClicked.AddDynamic(
			this, &UGameEndWidget::OnRestartButtonClicked
		);
	}
}

void UGameEndWidget::CleanUpAllUI()
{
	// Get All Widgets
	TArray<UUserWidget*> AllWidgets;
	UWidgetBlueprintLibrary::GetAllWidgetsOfClass(GetWorld(), AllWidgets, UUserWidget::StaticClass(), false);

	for (UUserWidget* Widget : AllWidgets)
	{
		if (Widget)
		{
			FString name = Widget->GetName();
			Widget->RemoveFromParent(); // remove from viewport
			Widget->MarkAsGarbage();  // markpendingkill

			UE_LOG(LogTemp, Warning, TEXT("Widget : %s has beened cleaned!"), *name);
			if (GEngine)
			{
				GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString::Printf(TEXT("Widget : %s has beened cleaned!"), *name));
			}
		}
	}

	UE_LOG(LogTemp, Warning, TEXT("All UI Widgets have been cleaned up."));
}


